package org.wlw.teacher.servlet;



import org.wlw.teacher.models.WebException;
import org.wlw.teacher.utils.Contrants;
import org.wlw.teacher.utils.DIUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    public BaseServlet() {
        DIUtils.di(this);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String m = req.getParameter("m");//此时得到了具体的一个方法
            if(m==null||"".equals(m)) {
                m = "index";
            }
            Class clz = this.getClass();
            Method method = clz.getMethod(m,HttpServletRequest.class,HttpServletResponse.class);
            String res = (String)method.invoke(this,req,resp);
            go(res,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if(cause instanceof WebException) {

                req.setAttribute("errorMsg",((WebException)cause).getMessage());
                go("/exception/web",req,resp);
            } else {
                e.printStackTrace();
            }
        }
    }

    private void go(String res, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        if(res.startsWith(Contrants.REDIR_PRE)) {
            //客户端跳转
            //获取去掉了redirect:之后的路径  redirect:/xx/xx
            String tpath = res.substring(Contrants.REDIR_PRE.length());
            System.out.println(tpath);
            resp.sendRedirect(req.getContextPath()+tpath);
        } else {
            req.getRequestDispatcher(Contrants.JSP_PREFIX+"/"+res+".jsp").forward(req,resp);
        }
    }

    protected String getRedirectUrl(String path) {
        return Contrants.REDIR_PRE+path;
    }
}
